<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="UTF-8">
    <title>日程表</title>
    <!-- Custom fonts for this template-->
    <link th:href="@{/vendor/fontawesome-free/css/all.min.css}" rel="stylesheet" type="text/css">
    <!-- Page level plugin CSS-->
    <link th:href="@{/vendor/datatables/dataTables.bootstrap4.css}" rel="stylesheet">
    <!-- Custom styles for this template-->
    <link th:href="@{/css/sb-admin.css}" rel="stylesheet">
    <!-- Bootstrap core JavaScript-->
    <script th:src="@{/vendor/jquery/jquery.min.js}"></script>
    <script th:src="@{/vendor/bootstrap/js/bootstrap.bundle.min.js}"></script>
    <!-- Core plugin JavaScript-->
    <script th:src="@{/vendor/jquery-easing/jquery.easing.min.js}"></script>
    <!-- Page level plugin JavaScript-->
    <script th:src="@{/vendor/datatables/jquery.dataTables.js}"></script>
    <script th:src="@{/vendor/datatables/dataTables.bootstrap4.js}"></script>
    <!-- Custom scripts for all pages-->
    <script th:src="@{/js/sb-admin.min.js}"></script>
    <!-- Demo scripts for this page-->
    <script th:src="@{/js/demo/datatables-demo.js}"></script>
</head>
<body  id="page-top">


<nav class="navbar navbar-expand navbar-dark bg-dark static-top">

    <a class="navbar-brand mr-1" th:href="@{/user/index}">日程云共享管理系统</a>


    <!-- Navbar -->
    <ul class="navbar-nav ml-auto ml-md-12" >

        <div th:if="${session.loginUser!=null}">
            <p th:text="${session.loginUser.getUsername()}" style="color:white"> </p>
        </div>
        <li class="nav-item dropdown no-arrow">
            <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="fas fa-user-circle fa-fw"></i>
            </a>
            <div class="dropdown-menu dropdown-menu-right" aria-labelledby="userDropdown">
                <a class="dropdown-item" href="#">个人设置</a>
                <a class="dropdown-item" th:href="@{/reset-password}">修改密码</a>
                <div class="dropdown-divider"></div>
                <div th:if="${session.loginUser!=null}">
                    <a class="dropdown-item" th:href="@{/logout}" data-toggle="modal" data-target="#logoutModal">注销</a>
                </div>
            </div>
        </li>
    </ul>

</nav>

<div id="wrapper">

    <!-- Sidebar -->
    <ul class="sidebar navbar-nav">
        <li class="nav-item">
            <a class="nav-link" href="#">
                <i class="fas fa-fw fa-tachometer-alt"></i>
                <span>Dashboard</span>
            </a>
        </li>
        <li class="nav-item ">
            <a class="nav-link" th:href="@{/share/community}">
                <i class="fas fa-fw fa-chart-area"></i>
                <span>用户共享社区</span></a>
        </li>
        <li class="nav-item">
            <a class="nav-link" th:href="@{/user/toScheduleframework}">
                <i class="fas fa-fw fa-chart-area"></i>
                <span>日程框架</span></a>
        </li>
        <li class="nav-item active">
            <a class="nav-link" th:href="@{/scheduletable/toScheduletable}">
                <i class="fas fa-fw fa-table"></i>
                <span>日程表</span></a>
        </li>
        <li class="nav-item ">
            <a class="nav-link" th:href="@{/scheduletemplate/toTemplate}">
                <i class="fas fa-fw fa-table"></i>
                <span>日程模版</span></a>
        </li>
        <li class="nav-item " shiro:hasRole="admin">
            <a class="nav-link" th:href="@{/admin/list}">
                <i class="fas fa-fw fa-table"></i>
                <span>用户列表</span></a>
        </li>
    </ul>

    <div id="content-wrapper">

        <div class="container-fluid">

            <!-- Breadcrumbs-->
            <ol class="breadcrumb">
                <li class="breadcrumb-item">
                    <a href="#">Dashboard</a>
                </li>
                <li class="breadcrumb-item active">日程表</li>
            </ol>



            <!-- Page Content -->

            <div class="card mb-3">
                <div class="card-header">
                    <div >
                    <i class="fas fa-table"></i>
                    日程表
                        <!-- 搜索 -->
                        <form class="d-none d-md-inline-block form-inline ml-auto mr-0 mr-md-3 my-2 my-md-0" method="get" th:action="@{/scheduletable/searchTable}">
                            <div class="input-group">
                                <input type="text" class="form-control" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2" name="value">
                                <div class="input-group-append">
                                    <button class="btn btn-primary" type="submit">
                                        <i class="fas fa-search"></i>
                                    </button>
                                </div>
                            </div>
                        </form>
                        <div style="float: right">
                            <button class="btn btn-primary" id="table_merge_modal_btn">合并日程表</button>
                            <button class="btn btn-primary" id="table_add_modal_btn">添加日程表</button>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-responsive-md text-nowrap">
                            <thead>
                                <tr>
                                    <th>id</th>
                                    <th>创建者</th>
                                    <th>日程表名</th>
                                    <th>当前状态</th>
                                    <th>操作</th>
                                    <th>公开/私有</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr th:each="table:${msg.get('page').list}">
                                    <th th:text="${table.getId()}">id</th>
                                    <th th:if="${session.loginUser!=null}" th:text="${session.loginUser.getUsername()}">创建者</th>
                                    <th th:text="${table.getName()}">日程表名</th>
                                    <th th:text="${table.getOpenState()==1?'公开':'私有'}">当前状态</th>
                                    <th>
                                        <button class="btn btn-primary btn-sm view_btn"  th:attr="view-id=${table.getId()}">查看</button>
                                        <button class="btn btn-primary btn-sm edit_btn"  th:attr="edit-id=${table.getId()}">修改</button>
                                        <button class="btn btn-primary btn-sm delete_btn" th:attr="del-id=${table.getId()}">删除</button>
                                        <a class="btn btn-primary btn-sm " th:href="@{'/share/copyTable/'+${table.getId()}}">复制</a>
                                    </th>
                                    <th>
                                        <a class="btn btn-primary btn-sm " th:text="${table.getOpenState()==0?'公开':'私有'}"
                                           th:href="@{'/share/open/'+${table.getId()}+'?flag='+${table.getOpenState()==1?'flase':'true'}}">公开</a>
                                    </th>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            <div class="card-footer small text-muted" th:each="page:${msg.get('page')}">
                <ul class="col-md-6">
                    <a>当前第[[${page.list.pageNum}]]页，总[[${page.list.pages}]]页，总[[${page.list.total}]]条记录</a>
                </ul>
                <nav aria-label="Page navigation example" style="float:right">
                    <ul class="pagination">
                        <li>
                        <li class="page-item"><a class="page-link" th:href="@{/scheduletable/toScheduletable}">首页</a></li>
                        </li>
                        <div>
                            <div class="clearfix">
                                <ul class="pagination m-b-5 pull-right">
                                    <li th:if="${page.hasPreviousPage}" class="page-item">
                                        <a class="page-link" th:href="@{'/scheduletable/toScheduletable?pageNum='+${page.prePage}}" >
                                            <i class="fa fa-angle-left"></i>上一页
                                        </a>
                                    </li>
                                    <th:block th:each="nav:${page.navigatepageNums}">
                                        <li class="page-item" th:classappend="${nav==page.list.pageNum}?'active':''">
                                            <a class="page-link" th:text="${nav}" th:href="@{'/scheduletable/toScheduletable?pageNum='+${nav}}"></a>
                                        </li>
                                    </th:block>
                                    <th:block th:if="${page.hasNextPage}">
                                        <li class="page-item">
                                            <a class="page-link" th:href="@{'/scheduletable/toScheduletable?pageNum='+${page.nextPage}}">
                                                下一页<i class="fa fa-angle-right"></i>
                                            </a>
                                        </li>
                                    </th:block>
                                </ul>
                            </div>
                        </div>
                        <li>
                            <li class="page-item"><a class="page-link" th:href="@{'/scheduletable/toScheduletable?pageNum='+${page.list.pages}}">末页</a></li>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>
        </div>
    </div>

        </div>
        <!-- /.container-fluid -->

        <!-- Sticky Footer -->
        <footer class="sticky-footer">
            <div class="container my-auto">
                <div class="copyright text-center my-auto">
                    <span>Copyright © Your Website 2019</span>
                </div>
            </div>
        </footer>

    </div>
    <!-- /.content-wrapper -->

</div>
<!-- /#wrapper -->

<!-- Scroll to Top Button-->
<a class="scroll-to-top rounded" href="#page-top">
    <i class="fas fa-angle-up"></i>
</a>

<!-- Logout Modal-->
<div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">确定退出登录吗?</h5>
                <button class="close" type="button" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">如果您准备结束当前会话，请在下面选择“退出”。</div>
            <div class="modal-footer">
                <button class="btn btn-secondary" type="button" data-dismiss="modal">取消</button>
                <a class="btn btn-primary" th:href="@{/logout}">退出</a>
            </div>
        </div>
    </div>
</div>

<!--合并日程表的模态框-->
<div class="modal" id="tableMergeModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">日程表合并</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form method="post" >
                    <div>
                        <p style="color: red" class="lead">请选择两个使用相同日程框架的日程表</p>
                    </div>
                    <!-- 所选择的日程表-->
                    <div class="form-group row">
                        <label  class="col-sm-4 col-form-label">日程表1:</label>
                        <div class="col-sm-8">
                            <select class="form-control"  id="table1" name="table1_Id">

                            </select>
                        </div>
                    </div>
                    <!-- 所选择的日程表-->
                    <div class="form-group row">
                        <label  class="col-sm-4 col-form-label">日程表2:</label>
                        <div class="col-sm-8">
                            <select class="form-control"  id="table2" name="table2_Id">

                            </select>
                        </div>
                    </div>
                    <!-- 合并后日程表的名字-->
                    <div class="form-group row">
                        <label  class="col-sm-4 col-form-label">合并后日程表的名字:</label>
                        <div class="col-sm-8">
                            <input type="text" class="form-control" id="name" name="name" required>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary"  id="merge">合并</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!--合并日程表的模态框-->
<div class="modal" id="MergeModal" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg modal-dialog-scrollable" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">日程表合并——解决冲突</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form method="post" >
                    <div>
                        <p style="color: red" class="lead">所选择两个日程表存在日程冲突，请选择需要保留的日程!</p>
                    </div>
                    <table class="table table-hover" id="clash_table">
                        <thead>
                            <tr>
                                <th>日程表1</th>
                                <th>日程表2</th>
                            </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary"  id="clash_merge">合并</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!--添加日程表的模态框-->
<div class="modal" id="tableAddModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">日程表添加</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form method="post" th:action="@{/scheduletable/createTable}" th:object="${table}">
                    <!--日程表名 -->
                    <div class="form-group row">
                        <label  class="col-sm-4 col-form-label">日程表名</label>
                        <div class="col-sm-8">
                            <input type="text" class="form-control"   th:field="*{name}">
                        </div>
                    </div>
                    <!-- 所选择的日程框架-->
                    <div class="form-group row">
                        <label  class="col-sm-4 col-form-label">选择一个日程框架:</label>
                        <div class="col-sm-8">
                            <select class="form-control"  th:field="*{scheduleframeworkId}">

                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                        <button type="submit" class="btn btn-primary"  >新增</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!--修改日程表的模态框-->
<div class="modal" id="tableupdateModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">日程表修改</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form method="post"  th:action="@{/scheduletable/updateTable}">
                    <!--id -->
                    <div class="form-group row" hidden>
                        <label  class="col-sm-4 col-form-label">id</label>
                        <div class="col-sm-8">
                            <input type="text" class="form-control"   id="tableId_update_static" name="scheduletableId">
                        </div>
                    </div>
                    <!--日程表名 -->
                    <div class="form-group row">
                        <label  class="col-sm-4 col-form-label">日程表名</label>
                        <div class="col-sm-8">
                            <input type="text" class="form-control"   id="tableName_update_input" name="name">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                        <button type="submit" class="btn btn-primary"  >修改</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!--删除日程表的模态框-->
<div class="modal" id="tabledeleteModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">日程表删除</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form method="post"  th:action="@{/scheduletable/delete}">
                    <div class="modal-body">确定要删除该日程表吗？删除日程表的同时会将日程表上的所有日程删除。如果仍然要删除的话请在下面选择“确认删除”。</div>
                    <!--id -->
                    <div class="form-group row" hidden>
                        <label  class="col-sm-4 col-form-label">id</label>
                        <div class="col-sm-8">
                            <input type="text" class="form-control"   id="tableId_delete_static" name="scheduletableId">
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                        <button type="submit" class="btn btn-primary"  >确认删除</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>

    // 获取所有已开放共享的日程框架
    function getFrameworks(ele){
        $(ele).empty();
        $.ajax({
            url:"http://localhost:8088/user/frameworks",
            type:"GET",
            success:function (result) {
                console.log(result);
                $.each(result.extend.frameworks,function (index,item) {
                    var optionEle=$("<option></option>").append(item.name).attr("value",item.id);
                    optionEle.appendTo(ele);
                });
            }
        });
    }

    //点击添加日程表，打开模态框
    $("#table_add_modal_btn").click(function () {
        getFrameworks("#tableAddModal select");
        $('#tableAddModal').modal({
            backdrop: "static"
        });
    });

    //得到日程表
    function getScheduletable(scheduletableId){
        $.ajax({
            url:"http://localhost:8088/scheduletable/getScheduletable/"+scheduletableId,
            type:"GET",
            success:function (result) {
                console.log(result);
                var data=result.extend.table;
                $("#tableId_update_static").val(data.id);
                $("#tableName_update_input").val(data.name);
                $("#tableId_delete_static").val(data.id);
            }
        });
    }

    //点击合并日程表，打开模态框
    $("#table_merge_modal_btn").click(function () {
        $("#name").empty();
        $.ajax({
           url:"http://localhost:8088/scheduletable/tables",
           type:"GET",
           success:function (result) {
                // console.log(result.extend.tables);
                var tables=result.extend.tables;
                if(JSON.stringify(tables)=="[]"){
                    alert("您还没有创建日程表，无法使用合并日程表!")
                }else{
                    $.each(tables,function (index,item) {
                        $("<option></option>").append(item.name).attr("value",item.id).appendTo("#table1");
                        $("<option></option>").append(item.name).attr("value",item.id).appendTo("#table2");
                    });
                    $("#tableMergeModal").modal({
                        backdrop: "static"
                    });
                }
           }
        });
    });

    //得到日程表所使用的的日程框架
    function checkFramework(scheduletableId){
        var frameworkId;
        $.ajax({
            url:"http://localhost:8088/scheduletable/getScheduletable/"+scheduletableId,
            type:"GET",
            async:false,
            success:function (result) {
                frameworkId=result.extend.table.scheduleframeworkId;
            }
        });
        return frameworkId;
    }

    //得到日程表的所有日程
    function checkSchedule(scheduletableId){
        var Schedules;
        $.ajax({
            url:"http://localhost:8088/scheduletable/getScheduletable/"+scheduletableId,
            type:"GET",
            async:false,
            success:function (result) {
                Schedules=result.extend.table.schedules;
            }
        });
        return Schedules;
    }

    //发送合并请求
    function merge(scheduleList,tableId,name){
        $.ajax({
            url:"http://localhost:8088/scheduletable/merge",
            type:"POST",
            dataType:"JSON",
            data:{
                scheduleList:JSON.stringify(scheduleList),
                tableId:tableId,
                name:name
            },
            success:function (result) {
                console.log(JSON.stringify(result));
                if(JSON.stringify(result.code)==200){
                    alert("合并成功");
                    location.href="http://localhost:8088/scheduletable/toScheduletable";
                }
            }
        });
    }

    //点击模态框里的合并按钮
    $("#merge").click(function () {
        var name=$("#name").val();
        var table1=$("#table1").val();
        var table2=$("#table2").val();
        if(table1==table2){
            return  alert("所选择的两个日程表都是同一个日程表，无需合并!");
        }
        var framework1=checkFramework(table1);
        var framework2=checkFramework(table2);
        if(framework1!=framework2){
            return  alert("所选择的两个日程表不是基于同一个日程框架所创建的日程表，无法合并!");
        }
        var schedules1=checkSchedule(table1);
        var schedules2=checkSchedule(table2);
        //如果表1和表2都为空
        if(JSON.stringify(schedules1)=="[]" && JSON.stringify(schedules2)=="[]") {
            return alert("所选择的两个日程表都是空的日程表，无需合并!")
        }
        //如果表1不为空，表2为空
        if(JSON.stringify(schedules1)!="[]" && JSON.stringify(schedules2)=="[]"){
            var scheduleList=schedules1;
            var tableId=table1;
            merge(scheduleList,tableId,name);
            return ;
        }
        //如果表1为空，表2不为空
        if(JSON.stringify(schedules1)=="[]" && JSON.stringify(schedules2)!="[]"){
            var scheduleList=schedules2;
            var tableId=table2;
            merge(scheduleList,tableId,name);
            return ;
        }
        //如果表1和表2都不为空，需要判断是否有日程冲突
        if(JSON.stringify(schedules1)!="[]" && JSON.stringify(schedules2)!="[]"){
            $("#clash_table tbody").empty();
            let schedule1=new Set(schedules1);//set集合存储日程表1所有的日程
            let schedule2=new Set(schedules2);//set集合存储日程表2所有的日程
            $.ajax({
                url:"http://localhost:8088/scheduletable/clashSchedules",
                type:"POST",
                dataType:"JSON",
                data:{
                    table1:table1,
                    table2:table2,
                },
                async:false,
                success:function (result) {
                    // console.log(result);
                    if(JSON.stringify(result.extend.clashSchedules)=="[]"){//表示没有冲突的日程
                        var scheduleList=Array.from(schedule1).concat(Array.from(schedule2));
                        var tableId=table1;
                        merge(scheduleList,tableId,name);
                        return ;
                    }else{//有冲突，需要解决冲突
                        // console.log("..............");
                        var chooseSchedules;
                        var clashSchedules=result.extend.clashSchedules;
                        var times=result.extend.times;
                        for(var i=0;i<clashSchedules.length;i++){
                            var clashTd=$("<tr></tr>");
                            for(var j=0;j<clashSchedules[i].length;j++){
                                console.log(result.extend.times);
                                clashTd.append($("<td><input type='radio' class='checked' name="+[i]+" value="+clashSchedules[i][j].id+" /></td>").append(clashSchedules[i][j].name+"["+clashSchedules[i][j].date.substring(0,10)+", "+times[i]+", "+clashSchedules[i][j].comments+"]"));
                                clashTd.appendTo("#clash_table tbody");
                            }
                        }
                        $("#MergeModal").modal({
                            backdrop: "static"
                        });
                        $("#clash_merge").click(function () {
                            var ids="";
                            var checked=document.getElementsByClassName("checked");
                            for(var i=0;i<checked.length;i++){
                                // console.log(t[i].checked);
                                if(checked[i].checked==true){
                                    // console.log(t[i].value);
                                    ids+=checked[i].value+"-";
                                }
                            }
                            // console.log(names);
                            ids=ids.substring(0,ids.length-1);
                            // console.log(ids);
                            $.ajax({
                                url:"http://localhost:8088/scheduletable/chooseSchedules",
                                type:"POST",
                                dataType:"JSON",
                                data:{
                                    ids:ids
                                },
                                async:false,
                                success:function (result) {
                                    // console.log(result.extend.chooseSchedules);
                                    chooseSchedules=result.extend.chooseSchedules;
                                }
                            });
                            var scheduleList=result.extend.schedulesList.concat(chooseSchedules);
                            // console.log(scheduleList);
                            var tableId=table1;
                            merge(scheduleList,tableId,name);
                            return ;
                        });
                    }
                }
            });

        }
    });

    //点击修改日程表按钮，打开模态框
    $(document).on("click",".edit_btn",function () {
        getScheduletable($(this).attr("edit-id"));
        $("#tableupdateModal").modal({
            backdrop:"static"
        });
    });

    //点击删除日程表按钮，打开模态框
    $(document).on("click",".delete_btn",function () {
        getScheduletable($(this).attr("del-id"));
        $("#tabledeleteModal").modal({
            backdrop:"static"
        });
    })

    //点击查看日程表按钮，跳转页面
    $(document).on("click",".view_btn",function () {
        var scheduletableId=$(this).attr("view-id");
        $.ajax({
            success : function(msg){
                window.location.href="http://localhost:8088/scheduletable/view/"+scheduletableId;
            }
        });
    })

</script>

</body>
</html>